#!/usr/bin/env python3
# coding:utf-8

"""
DAS主入口文件
"""

__author__ = 'MC'


import sys
import traceback
import logging

import commands
import cerror
import loadconfig


def Main():
    logging.basicConfig(format="%(asctime)s [%(levelname)s] [%(filename)s] %(message)s",
                        filename=loadconfig.LogPath + "/Error.log")
    print("欢迎使用数据库管理系统DAS")
    print("Version:0.1.1")
    # 初始化指令集
    Ccommands = commands.Command()
    Ccommands.Init()
    while True:
        Command = input(">>> ")
        if Command == 'Exit':
            break
        try:
            for Key in Ccommands.Command:
                ComArr = Ccommands.Command[Key][1].match(Command)
                if ComArr:
                    if ComArr.group('Command') == "Show":
                        Ccommands.Command["Show"][0](ComArr.group('Action'))
                    if ComArr.group('Command') == "Config":
                        Ccommands.Command['Config'][0](Action=ComArr.group('Action'), Name=ComArr.group('Name'), Value=ComArr.group('Value'))
                    if ComArr.group('Command') == "Backup":
                        Ccommands.Command['Backup'][0](LinkName=ComArr.group('LinkName'), FilePath=ComArr.group('FilePath'))
                    if ComArr.group('Command') == "Help":
                        Ccommands.Command['Help'][0](ComArr.group('Action'))
                    if ComArr.group('Command') == "Del":
                        Ccommands.Command['Del'][0](Action=ComArr.group('Action'), Name=ComArr.group('Name'))
                    if ComArr.group('Command') == "Test":
                        Ccommands.Command['Test'][0](Name=ComArr.group('Name'))
                    if ComArr.group('Command') == "Sys":
                        Ccommands.Command['Sys'][0](Action=ComArr.group('Action'), Value=ComArr.group('Value'))
                    break
            else:
                raise cerror.CommandError("不存在的指令 {0} ,请使用：Help List获取指令列表".format(Command))
        except cerror.CommandError as E:
            print(E.Message)
        except Exception:
            print("系统错误：请查看程序目录下/Log/Error.log文件")
            E_Type, E_Value, E_TB = sys.exc_info()
            Trace_FileName, Trace_LineNo, Trace_FunName, Trace_Source = traceback.extract_tb(E_TB)[0]
            logging.error("[File:{0}] [LineNo:{1}] [Mes:{2}] [Source:{3}]".format(Trace_FileName, Trace_LineNo, E_Value, Trace_Source))


if __name__ == "__main__":
    Main()
